/*
用户相关 api 接口
其中 由于 web 端没有对应接口
GetUsers EditUser DeleteUser ChangeUserPassword 函数未使用
*/

package v1

import (
    "net/http"
    "strconv"

    "gitee.com/keeving/quanta-test-cat/middleware"
    "gitee.com/keeving/quanta-test-cat/model"
    "gitee.com/keeving/quanta-test-cat/utils/errmsg"
    "gitee.com/keeving/quanta-test-cat/utils/validator"
    "github.com/gin-gonic/gin"
)

// AddUser 添加用户
func AddUser(c *gin.Context) {
    var data model.User
    var msg string
    var validCode int
    _ = c.ShouldBindJSON(&data)

    msg, validCode = validator.Validate(&data)
    if validCode != errmsg.SUCCESS {
        c.JSON(
            http.StatusOK, gin.H{
                "code":  validCode,
                "msg": msg,
            },
        )
        c.Abort()
        return
    }

    code := model.CheckUser(data.Username)
    if code == errmsg.SUCCESS {
        model.CreateUser(&data)
    }

    c.JSON(
        http.StatusOK, gin.H{
            "code":  code,
            "msg": errmsg.GetErrMsg(code),
        },
    )
}

// GetUserInfo 查询单个用户
func GetUserInfo(c *gin.Context) {
    tokenString := c.GetHeader("Authorization")
    username, _ := middleware.GetUserNameFromToken(tokenString)
    var maps = make(map[string]interface{})
    data, code := model.GetUserFromName(username)
    maps["username"] = data.Username
    maps["avatar"] = data.Avatar
    c.JSON(
        http.StatusOK, gin.H{
            "code":  code,
            "data":    maps,
            "msg": errmsg.GetErrMsg(code),
        },
    )
}

// GetUsers 查询用户列表
func GetUsers(c *gin.Context) {
    pageSize, _ := strconv.Atoi(c.Query("pagesize"))
    pageNum, _ := strconv.Atoi(c.Query("pagenum"))
    username := c.Query("username")

    switch {
    case pageSize >= 100:
        pageSize = 100
    case pageSize <= 0:
        pageSize = 10
    }

    if pageNum == 0 {
        pageNum = 1
    }

    data, total := model.GetUsers(username, pageSize, pageNum)

    code := errmsg.SUCCESS
    c.JSON(
        http.StatusOK, gin.H{
            "status":  code,
            "data":    data,
            "total":   total,
            "message": errmsg.GetErrMsg(code),
        },
    )
}

// EditUser 编辑用户
func EditUser(c *gin.Context) {
    var data model.User
    id, _ := strconv.Atoi(c.Param("id"))
    _ = c.ShouldBindJSON(&data)

    code := model.CheckUpUser(id, data.Username)
    if code == errmsg.SUCCESS {
        model.EditUser(id, &data)
    }

    c.JSON(
        http.StatusOK, gin.H{
            "status":  code,
            "message": errmsg.GetErrMsg(code),
        },
    )
}

// ChangeUserPassword 修改密码
func ChangeUserPassword(c *gin.Context) {
    var data model.User
    id, _ := strconv.Atoi(c.Param("id"))
    _ = c.ShouldBindJSON(&data)

    code := model.ChangePassword(id, &data)

    c.JSON(
        http.StatusOK, gin.H{
            "status":  code,
            "message": errmsg.GetErrMsg(code),
        },
    )
}

// DeleteUser 删除用户
func DeleteUser(c *gin.Context) {
    id, _ := strconv.Atoi(c.Param("id"))

    code := model.DeleteUser(id)

    c.JSON(
        http.StatusOK, gin.H{
            "status":  code,
            "message": errmsg.GetErrMsg(code),
        },
    )
}


func Logout(c *gin.Context) {
    // 从请求头中获取 Token
    tokenString := c.GetHeader("Authorization")
    if tokenString == "" {
        c.JSON(http.StatusBadRequest, gin.H{
            "code": 500,
            "msg":  "缺少 Token",
            "data": nil,
        })
        return
    }

    if middleware.IsTokenBlacklisted(tokenString) {
        c.JSON(http.StatusUnauthorized, gin.H{
            "code": 401,
            "msg":  "Token 已失效",
            "data": nil,
        })
        c.Abort()
        return
    }
    
    // 将 Token 添加到黑名单中
    middleware.AddToBlacklist(tokenString)

    c.JSON(http.StatusOK, gin.H{
        "code": 200,
        "msg":  "操作成功",
        "data": nil,
    })
}

// 查询用户写的文章
func GetUserArticles(c *gin.Context) {
    tokenString := c.GetHeader("Authorization")
    username, _ := middleware.GetUserNameFromToken(tokenString)
    userid, _ := model.GetUserIDByUsername(username)
    data, total, code := model.GetUserArticles(userid)
    
    if code != errmsg.SUCCESS {
        c.JSON(http.StatusOK, gin.H{
            "code": code,
            "msg":   errmsg.GetErrMsg(code),
        })
    }
    c.JSON(http.StatusOK, gin.H{
        "code":  errmsg.SUCCESS,
        "data":    gin.H{
            "num": total,
            "articles": data,
        },
        "msg": errmsg.GetErrMsg(errmsg.SUCCESS),
    })
}

// 查询用户喜欢的文章
func GetUserLikes(c *gin.Context) {
    tokenString := c.GetHeader("Authorization")
    username, _ := middleware.GetUserNameFromToken(tokenString)
    userid, _ := model.GetUserIDByUsername(username)
    data, code:= model.GetUserLikes(userid)
    
    var result []gin.H
    total := len(data)

    for _, article := range data {
        result = append(result, gin.H{
            "id":    article.ID,
            "title": article.Title,
            "img":   article.Img,
        })
    }

    if code == errmsg.SUCCESS {
        c.JSON(http.StatusOK, gin.H{
            "code": code,
            "msg":   errmsg.GetErrMsg(code),
            "data": gin.H{
                "num": total,
                "articles": result,
            },
        })
    } else {
        c.JSON(http.StatusOK, gin.H{
            "code": code,
            "msg":   errmsg.GetErrMsg(code),
            "data": nil,
        })
    }
}